﻿using System;
using System.Linq;
using System.Security;
using Peak.Core.DataInterfaces;
using System.Security.Principal;
using Peak.Core;

namespace Peak.ApplicationServices.Services
{
  public class StoryService : IStoryService
  {
    readonly IStoryRepository _storyRepository;
    private readonly IPrincipal _principal;

    public StoryService(IStoryRepository storyRepository, IPrincipal principal)
    {
      _storyRepository = storyRepository;
      _principal = principal;
    }

    public Story Get(int id)
    {
      Story story = _storyRepository.Get(id);
      if(story == null || story.Project.Users.FirstOrDefault(f=>f.UserName.ToLower()== _principal.Identity.Name.ToLower()) == null)
      {
        throw new EntityNotFoundException();
      }
      return story;
    }

    public Story Update(Story story)
    {
      if(story == null)
      {
        throw new ArgumentNullException("story");
      }
      if (story.Project.Users.FirstOrDefault(f => f.UserName.ToLower() == _principal.Identity.Name.ToLower()) == null)
      {
        throw new SecurityException();
      }
      return _storyRepository.SaveOrUpdate(story);
    }


    public Page<Story> GetPage(StoryFilter sf)
    {
      return _storyRepository.GetPage(sf);
    }


    public void Delete(Story story)
    {
      if (story == null)
      {
        throw new ArgumentNullException("story");
      }
      if (story.Project.Users.FirstOrDefault(f => f.UserName.ToLower() == _principal.Identity.Name.ToLower()) == null)
      {
        throw new SecurityException();
      }
      _storyRepository.Delete(story);
    }
  }
}
